package com.example.paizhaogou;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.paizhaogou.Adapter.ItemRecycleAdapter;
import com.example.paizhaogou.Entity.Item;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class resultActivity extends AppCompatActivity {
    private static Uri imageUri;
    private String mFilePath;
    private RecyclerView recyclerView;
    private ImageView imageView;
    private TextView textView;
    private String itemName;
    private List<Item> items;
    private ItemRecycleAdapter itemRecycleAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recyclerview);
//        imageView = findViewById(R.id.imageView);
        recyclerView = findViewById(R.id.recycler);
        textView=findViewById(R.id.textView);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String uriStr = bundle.getString("uri");
        imageUri = Uri.parse(uriStr);//得到图片uri
        mFilePath = getFilePathFromUri(resultActivity.this, imageUri);
        FileInputStream fis;
        Bitmap bitmap = null;
        try {
            fis = new FileInputStream(mFilePath);
            bitmap = BitmapFactory.decodeFile(mFilePath);//得到bitmap
            //对bitmap小进行压缩
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;//缩小四倍
            bitmap = BitmapFactory.decodeFile(mFilePath, options);
            Log.e("bitmap size", bitmap.getByteCount() + "");
            bitmap = changeBitmapSize(bitmap);
//            imageView.setImageBitmap(bitmap);
            Log.d("get bitmap", "get success!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (bitmap == null) {
            Toast.makeText(getApplicationContext(), "获取图片失败！", Toast.LENGTH_SHORT).show();
        } else {
            JdScan jdScan=new JdScan();
            jdScan.postToJd(bitmap, resultActivity.this, getAssets(), getResources());
            while(!jdScan.isFlag()){
                continue;
            }
            items=jdScan.getItems();
            recyclerView.setLayoutManager(new LinearLayoutManager(resultActivity.this,
                    LinearLayoutManager.VERTICAL,false));

            itemRecycleAdapter=new ItemRecycleAdapter(items,resultActivity.this);
            //设置动画
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(itemRecycleAdapter);
        }
        Toast.makeText(getApplicationContext(), "识别完毕!", Toast.LENGTH_SHORT).show();
    }

    private Bitmap changeBitmapSize(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Log.e("width", "width:" + width);
        Log.e("height", "height:" + height);
        //设置想要的大小
        int newWidth = 689;
        int newHeight = 502;

        //计算压缩的比率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        //获取想要缩放的matrix
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        //获取新的bitmap
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        bitmap.getWidth();
        bitmap.getHeight();
        Log.e("newWidth", "newWidth" + bitmap.getWidth());
        Log.e("newHeight", "newHeight" + bitmap.getHeight());
        //旋转图片
        bitmap = adjustPhotoRotation(bitmap, 90);
        return bitmap;
    }

    public static String getFilePathFromUri(Context context, Uri uri) {  //从uri中得到path
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns
                    .DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 调整bitmap的角度
     *
     * @param bitmap
     * @param orientationDegree
     * @return
     */
    public static Bitmap adjustPhotoRotation(Bitmap bitmap, int orientationDegree) {

        Matrix matrix = new Matrix();
        matrix.setRotate(orientationDegree, (float) bitmap.getWidth() / 2,
                (float) bitmap.getHeight() / 2);
        float targetX, targetY;
        if (orientationDegree == 90) {
            targetX = bitmap.getHeight();
            targetY = 0;
        } else {
            targetX = bitmap.getHeight();
            targetY = bitmap.getWidth();
        }


        final float[] values = new float[9];
        matrix.getValues(values);


        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];


        matrix.postTranslate(targetX - x1, targetY - y1);


        Bitmap canvasBitmap = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getWidth(),
                Bitmap.Config.ARGB_8888);


        Paint paint = new Paint();
        Canvas canvas = new Canvas(canvasBitmap);
        canvas.drawBitmap(bitmap, matrix, paint);


        return canvasBitmap;
    }

}